package com.bangmai.util;

import java.io.ByteArrayOutputStream;
import java.io.DataOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.StringReader;
import java.io.UnsupportedEncodingException;
import java.net.SocketException;
import java.net.URLEncoder;
import java.util.Date;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.logging.Logger;

import org.apache.commons.codec.binary.Base64;
import org.apache.commons.net.ftp.FTP;
import org.dom4j.Attribute;
import org.dom4j.io.SAXReader;
import org.jdom2.Document;
import org.jdom2.Element;
import org.jdom2.JDOMException;
import org.jdom2.input.SAXBuilder;
import org.jdom2.output.Format;
import org.jdom2.output.XMLOutputter;
import org.slf4j.helpers.FormattingTuple;
import org.springframework.aop.ThrowsAdvice;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.xml.sax.InputSource;

import com.bangmai.beans.Order2CommodityInspection;
import com.bangmai.beans.Order2Customer;
import com.bangmai.beans.Order2Immigration;
import com.bangmai.beans.Order2Payment;
import com.bangmai.beans.Order2QiBang;
import com.bangmai.beans.Order2StockOut;
import com.bangmai.beans.OrderBody2Payment;
import com.bangmai.beans.OrderGood2CommodityInspection;
import com.bangmai.beans.OrderGood2Customer;
import com.bangmai.beans.OrderGood2Immigration;
import com.bangmai.beans.OrderGood2QiBang;
import com.bangmai.beans.OrderGood2StockOut;
import com.bangmai.beans.QiBangOrderItemList;
import com.bangmai.beans.QiBangRoot;
import com.bangmai.config.Config;
import com.bangmai.exception.ServiceException;
import com.bangmai.model.OrderMapper;
import com.bangmai.model.OrderStatus;
import com.bangmai.model.OrderStatusMapper;
import com.bangmai.model.Receiver;

/**
 * XML操作工具类
 * 
 * @author dellpc
 *
 */
@Component
public class XmlUtil {
	private static Logger logger = Logger.getLogger(XmlUtil.class.getName());
	@Autowired
	private OrderStatusMapper orderStatusMapper;
	@Autowired
	private PropertyUtil propertyUtil;

	/**
	 * 海关 创建报文并发送报文
	 * 
	 * @param order2Customer
	 * @param goods
	 * @throws Exception
	 */

	public boolean createCustomXml(Order2Customer order2Customer, List<OrderGood2Customer> goods) throws Exception {
		Element root = new Element("Manifest");
		Document document = new Document(root);
		Element head = new Element("Head");
		head.addContent(new Element("MessageID").setText(order2Customer.MessageID));
		head.addContent(new Element("MessageType").setText(order2Customer.MessageType));
		head.addContent(new Element("SenderID").setText(order2Customer.SenderID));
		head.addContent(new Element("SendTime").setText(order2Customer.SendTime));
		head.addContent(new Element("Version").setText(order2Customer.Version));
		root.addContent(head);

		Element Declaration = new Element("Declaration");
		Element EOrder = new Element("EOrder");
		EOrder.addContent(new Element("OrderId").setText(order2Customer.OrderId));
		EOrder.addContent(new Element("IEFlag").setText(order2Customer.IEFlag));
		EOrder.addContent(new Element("OrderStatus").setText(order2Customer.OrderStatus));
		EOrder.addContent(new Element("EntRecordNo").setText(order2Customer.EntRecordNo));
		EOrder.addContent(new Element("EntRecordName").setText(order2Customer.EntRecordName));
		EOrder.addContent(new Element("OrderName").setText(order2Customer.OrderName));
		EOrder.addContent(new Element("OrderDocType").setText(order2Customer.OrderDocType));
		EOrder.addContent(new Element("OrderDocId").setText(order2Customer.OrderDocId));
		EOrder.addContent(new Element("OrderPhone").setText(order2Customer.OrderPhone));
		EOrder.addContent(new Element("OrderGoodTotal").setText(order2Customer.OrderGoodTotal));
		EOrder.addContent(new Element("OrderGoodTotalCurr").setText(order2Customer.OrderGoodTotalCurr));
		EOrder.addContent(new Element("Freight").setText(order2Customer.Freight));
		EOrder.addContent(new Element("FreightCurr").setText(order2Customer.FreightCurr));
		EOrder.addContent(new Element("Tax").setText(order2Customer.Tax));
		EOrder.addContent(new Element("TaxCurr").setText(order2Customer.TaxCurr));
		EOrder.addContent(new Element("Note").setText(order2Customer.Note));
		EOrder.addContent(new Element("OrderDate").setText(order2Customer.OrderDate));
		Declaration.addContent(EOrder);
		root.addContent(Declaration);

		Element EOrderGoods = new Element("EOrderGoods");

		for (int i = 0; i < goods.size(); i++) {
			Element EOrderGood = new Element("EOrderGood");
			EOrderGood.addContent(new Element("GNo").setText(goods.get(i).GNo));
			EOrderGood.addContent(new Element("ChildOrderNo").setText(goods.get(i).ChildOrderNo));
			EOrderGood.addContent(new Element("StoreRecordNo").setText(goods.get(i).StoreRecordNo));
			EOrderGood.addContent(new Element("StoreRecordName").setText(goods.get(i).StoreRecordName));
			EOrderGood.addContent(new Element("CustomsListNO").setText(goods.get(i).CustomsListNO));
			EOrderGood.addContent(new Element("DecPrice").setText(goods.get(i).DecPrice));
			EOrderGood.addContent(new Element("Unit").setText(goods.get(i).Unit));
			EOrderGood.addContent(new Element("GQty").setText(goods.get(i).GQty));
			EOrderGood.addContent(new Element("DeclTotal").setText(goods.get(i).DeclTotal));
			EOrderGood.addContent(new Element("Notes").setText(goods.get(i).Notes));
			EOrderGoods.addContent(EOrderGood);
		}
		Declaration.addContent(EOrderGoods);
		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);
		String filepath = propertyUtil.getHg_file_path();
		String filename = order2Customer.MessageType + TimeUtil.getTimeString2() + "_" + FileUtil.get3RandomString()+ ".xml";
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + "/" + filename));

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			xmlOutputter = null;
		}
		String xmlString = null;
		try {
			xmlString = FileUtil.readFile(filepath + "/" + filename);
			System.out.println(xmlString);

			AESMessageSigner signer = new AESMessageSigner();
			xmlString = signer.encrypt(xmlString.getBytes());

		} catch (Exception e) {
			e.getMessage();
		}
		FileWriter writer = null;
		try {
			// 清空原来的内容，把加密之后的写进去
			File file = new File(filepath + "/" + filename);
			writer = new FileWriter(file);
			writer.write("");
			FileUtil.saveFile(filepath + "/" + filename, xmlString);
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			try {
				writer.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		boolean isSuccess = false;
		try {
			isSuccess = FTPClientUtil.transferFile(Config.FTP_CUSTOM_HOST, Config.FTP_CUSTOM_PORT,
					Config.FTP_CUSTOM_USERNAME, Config.FTP_CUSTOM_PASSWORD, Config.FTP_CUSTOM_UPLOAD_FILEPATH, true,
					filepath + "/" + filename, "", "");
		} catch (SocketException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

		return isSuccess;

	}

	/**
	 * 商检 创建报文和发送报文
	 * 
	 * @param goods
	 *            ��Ʒ
	 * @param order
	 *            ����
	 * @throws Exception
	 */

	public boolean createCommodityInspectionXml(Order2CommodityInspection order,
			List<OrderGood2CommodityInspection> goods) throws Exception {

		Element root = new Element("ROOT");
		Document document = new Document(root);
		Element head = new Element("Head");
		// 报文头
		head.addContent(new Element("MessageID").setText(order.getMessageID()));
		head.addContent(new Element("MessageType").setText(order.getMessageType()));
		head.addContent(new Element("Receiver").setText(order.getReceiver()));
		head.addContent(new Element("Sender").setText(order.getSender()));
		head.addContent(new Element("SendTime").setText(order.getSendTime()));
		head.addContent(new Element("FunctionCode").setText(order.getFunctionCode()));
		head.addContent(new Element("Version").setText(order.getVersion()));
		root.addContent(head);
		Element body = new Element("Body");
		Element swbebtrade = new Element("swbebtrade");
		Element record = new Element("Record");
		// body �ж�����Ϣ
		record.addContent(new Element("EntInsideNo").setText(order.getEntInsideNo()));
		record.addContent(new Element("Ciqbcode").setText(order.getCiqbcode()));
		record.addContent(new Element("CbeComcode").setText(order.getCbeComcode()));
		record.addContent(new Element("CbepComcode").setText(order.getCbepComcode()));
		record.addContent(new Element("OrderStatus").setText(order.getOrderStatus()));
		record.addContent(new Element("ReceiveName").setText(order.getReceiveName()));
		record.addContent(new Element("ReceiveAddr").setText(order.getReceiveAddr()));
		record.addContent(new Element("ReceiveNo").setText(order.getReceiveNo()));
		record.addContent(new Element("ReceivePhone").setText(order.getReceivePhone()));
		record.addContent(new Element("FCY").setText(order.getFCY()));
		record.addContent(new Element("Fcode").setText(order.getFcode()));
		record.addContent(new Element("Editccode").setText(order.getEditccode()));
		record.addContent(new Element("DrDate").setText(order.getDrDate()));
		swbebtrade.addContent(record);
		body.addContent(swbebtrade);
		root.addContent(body);
		Element swbebtrade_good = new Element("swbebtradeg");
		for (int i = 0; i < goods.size(); i++) {
			Element Record = new Element("Record");
			Record.addContent(new Element("EntGoodsNo").setText(goods.get(i).getEntGoodsNo()));
			Record.addContent(new Element("Gcode").setText(goods.get(i).getGcode()));
			Record.addContent(new Element("Hscode").setText(goods.get(i).getHscode()));
			Record.addContent(new Element("CiqGoodsNo").setText(goods.get(i).getCiqGoodsNo()));
			Record.addContent(new Element("CopGName").setText(goods.get(i).getCopGName()));
			Record.addContent(new Element("Brand").setText(goods.get(i).getBrand()));
			Record.addContent(new Element("Spec").setText(goods.get(i).getSpec()));
			Record.addContent(new Element("Origin").setText(goods.get(i).getOrigin()));
			Record.addContent(new Element("Qty").setText(goods.get(i).getQty()));
			Record.addContent(new Element("QtyUnit").setText(goods.get(i).getQtyUnit()));
			Record.addContent(new Element("DecPrice").setText(goods.get(i).getDecPrice()));
			Record.addContent(new Element("DecTotal").setText(goods.get(i).getDecTotal()));
			Record.addContent(new Element("SellWebSite").setText(goods.get(i).getSellWebSite()));
			Record.addContent(new Element("Nots").setText(goods.get(i).getNots()));
			swbebtrade_good.addContent(Record);
		}
		record.addContent(swbebtrade_good);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = propertyUtil.getSj_file_path();
		logger.info(filepath);

		String filename = order.MessageType + "_" + TimeUtil.getTimeString2() + "_" + FileUtil.get3RandomString()
				+ ".xml";
		FileWriter writer = null;
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + "/" + filename));
			String packetXml = FileUtil.readFile(filepath + "/" + filename);
			packetXml = packetXml.replace("<FunctionCode />", "<FunctionCode></FunctionCode>");
			packetXml = packetXml.replace("<Nots />", "<Nots></Nots>");
			packetXml = packetXml.replace("<CiqGoodsNo />", "<CiqGoodsNo></CiqGoodsNo>");
			// 将原来的 XML文件内容清空
			File file = new File(filepath + "/" + filename);
			writer = new FileWriter(file);
			writer.write("");
			FileUtil.saveFile(filepath + "/" + filename, packetXml);
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			fm = null;
			writer.close();
			xmlOutputter = null;
		}

		boolean isSuccess = false;
		isSuccess = FTPClientUtil.transferFile(Config.FTP_CCIQ_IP, Config.FTP_CCIQ_PORT, Config.FTP_CCIQ_USERNAME,
				Config.FTP_CCIQ_PASSWORD, Config.FTP_CCIQ_UPLOADPATH, true, filepath + "/" + filename, "", "");

		return isSuccess;

	}

	/**
	 * 通联支付
	 * 
	 * @param oPayment
	 * 
	 * @param list
	 * @throws Exception
	 * 
	 */

	public Receiver createPaymentXml(Order2Payment oPayment, List<OrderBody2Payment> list, String... strings)
			throws Exception {
		if (oPayment == null || list.isEmpty()) {
			return null;
		}

		Receiver receiver = new Receiver();
		Element root = new Element("VnbMessage");
		Document document = new Document(root);
		Element MessageHead = new Element("MessageHead");
		MessageHead.addContent(new Element("MessageCode").setText(oPayment.getMessageCode()));
		MessageHead.addContent(new Element("MessageID").setText(oPayment.getMessageID()));
		MessageHead.addContent(new Element("SenderID").setText(oPayment.getSenderID()));
		MessageHead.addContent(new Element("SendTime").setText(oPayment.getSendTime()));
		MessageHead.addContent(new Element("Sign").setText(oPayment.getSign()));
		root.addContent(MessageHead);

		Element MessageBodyList = new Element("MessageBodyList");
		for (int i = 0; i < list.size(); i++) {
			Element MessageBody = new Element("MessageBody");
			MessageBody.addContent(new Element("customICP").setText(list.get(i).getCustomICP()));
			MessageBody.addContent(new Element("ciqType").setText(list.get(i).getCiqType()));
			MessageBody.addContent(new Element("cbepComCode").setText(list.get(i).getCbepComCode()));
			MessageBody.addContent(new Element("orderNo").setText(list.get(i).getOrderNo()));
			MessageBody.addContent(new Element("payTransactionNo").setText(list.get(i).getPayTransactionNo()));
			MessageBody.addContent(new Element("payChnlID").setText(list.get(i).getPayChnlID()));
			MessageBody.addContent(new Element("payTime").setText(list.get(i).getPayTime()));
			MessageBody.addContent(new Element("payGoodsAmount").setText(list.get(i).getPayGoodsAmount()));
			MessageBody.addContent(new Element("payTaxAmount").setText(list.get(i).getPayTaxAmount()));
			MessageBody.addContent(new Element("freight").setText(list.get(i).getFreight()));
			MessageBody.addContent(new Element("payCurrency").setText(list.get(i).getPayCurrency()));
			MessageBody.addContent(new Element("payerName").setText(list.get(i).getPayerName()));
			MessageBody.addContent(new Element("payerDocumentType").setText(list.get(i).getPayerDocumentType()));
			MessageBody.addContent(new Element("payerDocumentNumber").setText(list.get(i).getPayerDocumentNumber()));
			MessageBodyList.addContent(MessageBody);
		}
		root.addContent(MessageBodyList);
		ByteArrayOutputStream byteRsp = new ByteArrayOutputStream();

		XMLOutputter xmlOut = new XMLOutputter();
		try {
			xmlOut.output(document, byteRsp);

		} catch (Exception e) {
			e.printStackTrace();
		}
		String filePath = Config.PAY_IN + "/" + TimeUtil.getTimeString1() + ".xml";
		saveXML(document, filePath);
		String xmlString = FileUtil.readFile(filePath);
		xmlString = xmlString.replace("<Sign />", "<Sign></Sign>");
		String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		xmlString = xmlString.replace(header, "");// 去掉XML头申明
		String signXML = Md5Util.getMD5ofByte((xmlString + Config.PAY_KEY).getBytes("utf-8"));// 报文头
		xmlString = header + xmlString.replace("<Sign></Sign>", "<Sign>" + signXML + "</Sign>");
		String receiverString = HttpRequestUtils.doPost(xmlString.getBytes(), Config.PAY_URL);
		// 解析回执
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build(new InputSource(new StringReader(receiverString)));
		Element roots = doc.getRootElement(); // 得到根元素
		List<Element> elements = roots.getChildren(strings[0]);
		for (Element element : elements) {
			if (!element.isRootElement()) {
				Element element2 = element.getChild(strings[1]);
				receiver.setCode(element2.getValue());
				if (element2.getValue() != null && element2.getValue().equals("BZ0001")) {
					receiver.setStatus("1");
					receiver.setInfo("请求已受理");
				} else {
					receiver.setStatus("0");
				}

			}

		}
		List<Element> elements2 = roots.getChildren(strings[2]);
		for (Element element : elements2) {
			if (!element.isRootElement()) {
				List<Element> elements3 = element.getChildren();
				for (Element element2 : elements3) {
					Element element3 = element2.getChild(strings[3]);
					receiver.setInfo(element3.getValue());
					Element element4 = element2.getChild(strings[4]);
					receiver.setOrder_id(element4.getValue());
				}

			}

		}
		receiver.setDate(new Date());
		receiver.setName("通联支付");

		return receiver;
	}

	/**
	 * 获取签名字段 sign
	 * 
	 * @param filepath
	 * @return
	 */

	public String getSign(String filepath) {
		String packetXmlString = null;

		try {
			packetXmlString = FileUtil.readFile(filepath);
			packetXmlString = packetXmlString.replace("<Sign />", "<Sign></Sign>");
			System.out.println(packetXmlString);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		int begin_index = packetXmlString.indexOf("<?");
		int end_index = packetXmlString.indexOf(">");
		String head = packetXmlString.substring(begin_index, end_index + 1);
		packetXmlString = packetXmlString.replace(head, "");// ȥ��XMLͷ����

		String sign = null;
		try {
			sign = Md5Util.getMD5ofByte((packetXmlString + Config.PAY_KEY).getBytes("utf-8"));
			sign = Md5Util.getMD5ofByte(sign.getBytes("utf-8"));
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} // ����ͷ sign�ֶε�ֵ
		return sign;
	}

	/**
	 * x修改某一个节点的值
	 * 
	 * @param filepath
	 *            文件全路径
	 * @param sign
	 *            节点名字
	 */
	public void updateXml(String filepath, String sign) {
		SAXBuilder saxBuilder = new SAXBuilder();
		Document document = null;
		try {
			document = saxBuilder.build(new File(filepath));
			Element root = document.getRootElement();
			Element element = root.getChild("MessageHead");
			Element element2 = element.getChild("Sign");
			System.out.println(element2.getName());
			element2.setText(sign);

		} catch (JDOMException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		saveXML(document, filepath);

	}

	// 填充签名
	public String update(String packetXmlString) throws IOException {

		String header = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>";
		packetXmlString = packetXmlString.replaceAll(header, "");// 去掉XML头申明
		System.err.println("去掉报文头->" + packetXmlString);
		String signXML = Md5Util.getMD5ofByte((packetXmlString + "3D7D15BA3FEF491F9096AC4CB7BB0893").getBytes("utf-8"));// 报文头
		System.out.println(signXML);
		packetXmlString = header + packetXmlString.replaceAll("<Sign></Sign>",
				"<Sign>" + "DAE550F03429EE741849D568AB1ACF46" + "</Sign>");
		System.out.println(packetXmlString);
		return packetXmlString;
		// 将原来的 XML文件内容清空
		// File file = new File(filePath);
		// FileWriter writer = new FileWriter(file);
		// writer.write("");
		// FileUtil.saveFile(filePath, packetXmlString);
	}

	/**
	 * 出库 创建报文并发送
	 * 
	 * @param order
	 * @param goods
	 * @throws ServiceException
	 * @throws IOException
	 * @throws SocketException
	 */
	public boolean createStockOutXml(Order2StockOut order, List<OrderGood2StockOut> goods)
			throws ServiceException, SocketException, IOException {
		boolean isSuccess = false;
		if (goods == null || goods.isEmpty()) {
			throw new ServiceException("订单号为：" + order.getOrderId() + "的订单中有商品查询不到信息");
		}

		Element root = new Element("Manifest");
		Document document = new Document(root);
		Element head = new Element("Head");
		head.addContent(new Element("MessageID").setText(order.MessageID));
		head.addContent(new Element("FunctionCode").setText(order.FunctionCode));
		head.addContent(new Element("MessageType").setText(order.MessageType));
		head.addContent(new Element("SenderID").setText(order.SenderID));
		head.addContent(new Element("SendTime").setText(order.SendTime));
		root.addContent(head);

		Element Declaration = new Element("Declaration");
		Element ExOrder = new Element("ExOrder");
		ExOrder.addContent(new Element("EntInsideNo").setText(order.EntInsideNo));
		ExOrder.addContent(new Element("InputDate").setText(order.InputDate));
		ExOrder.addContent(new Element("DrDate").setText(order.DrDate));
		ExOrder.addContent(new Element("Nots").setText(order.Nots));
		ExOrder.addContent(new Element("IEFlag").setText(order.IEFlag));
		ExOrder.addContent(new Element("NetWt").setText(order.NetWt));
		ExOrder.addContent(new Element("GrossWt").setText(order.GrossWt));
		ExOrder.addContent(new Element("Num").setText(order.Num));
		ExOrder.addContent(new Element("GoodInfo").setText(order.GoodInfo));
		ExOrder.addContent(new Element("RecipientName").setText(order.RecipientName));
		ExOrder.addContent(new Element("RecipientCountryCode").setText(order.RecipientCountryCode));
		ExOrder.addContent(new Element("RecipientProvincesCode").setText(order.RecipientProvincesCode));
		ExOrder.addContent(new Element("RecipientDetailedAddress").setText(order.RecipientDetailedAddress));
		ExOrder.addContent(new Element("RecipientPhone").setText(order.RecipientPhone));
		ExOrder.addContent(new Element("ReceiveNo").setText(order.ReceiveNo));
		ExOrder.addContent(new Element("OrderName").setText(order.OrderName));
		ExOrder.addContent(new Element("OrderDocType").setText(order.OrderDocType));
		ExOrder.addContent(new Element("OrderDocId").setText(order.OrderDocId));
		ExOrder.addContent(new Element("OrderId").setText(order.OrderId));
		ExOrder.addContent(new Element("OrderEntRecordNo").setText(order.OrderEntRecordNo));
		ExOrder.addContent(new Element("ExpressCo").setText(order.ExpressCo));
		ExOrder.addContent(new Element("CiqBusiMode").setText(order.CiqBusiMode));
		ExOrder.addContent(new Element("CiqEnorderCode").setText(order.CiqEnorderCode));
		ExOrder.addContent(new Element("CiqBcode").setText(order.CiqBcode));
		ExOrder.addContent(new Element("CiqFcy").setText(order.CiqFcy));
		ExOrder.addContent(new Element("CiqCbeComcode").setText(order.CiqCbeComcode));
		ExOrder.addContent(new Element("CiqCbepcomcode").setText(order.CiqCbepcomcode));
		ExOrder.addContent(new Element("ExpressProv").setText(order.ExpressProv));
		ExOrder.addContent(new Element("ExpressCity").setText(order.ExpressCity));
		ExOrder.addContent(new Element("ExpressArea").setText(order.ExpressArea));
		ExOrder.addContent(new Element("ExpressRemarks").setText(order.ExpressRemarks));
		ExOrder.addContent(new Element("NeedList").setText(order.NeedList));
		ExOrder.addContent(new Element("NeedInvoice").setText(order.NeedInvoice));
		ExOrder.addContent(new Element("InvoiceType").setText(order.InvoiceType));
		ExOrder.addContent(new Element("InvoiceTitle").setText(order.InvoiceTitle));
		ExOrder.addContent(new Element("InvoiceContent").setText(order.InvoiceContent));
		ExOrder.addContent(new Element("CiqPayComcode").setText(order.CiqPayComcode));
		ExOrder.addContent(new Element("CiqPayno").setText(order.CiqPayno));
		ExOrder.addContent(new Element("CiqPayorName").setText(order.CiqPayorName));
		ExOrder.addContent(new Element("CiqPayFcy").setText(order.CiqPayFcy));
		ExOrder.addContent(new Element("CiqPayFcode").setText(order.CiqPayFcode));
		ExOrder.addContent(new Element("CiqPayDate").setText(order.CiqPayDate));
		ExOrder.addContent(new Element("Freight").setText(order.Freight));
		ExOrder.addContent(new Element("ValuationFee").setText(order.ValuationFee));
		ExOrder.addContent(new Element("ExpressNo").setText(order.ExpressNo));
		ExOrder.addContent(new Element("NeedWmsOper").setText(order.NeedWmsOper));

		ExOrder.addContent(new Element("LogisticsProviders").setText(order.LogisticsProviders));
		ExOrder.addContent(new Element("CustomerCode").setText(order.CustomerCode));
		ExOrder.addContent(new Element("InternetDomainName").setText(order.InternetDomainName));
		ExOrder.addContent(new Element("RecipientProvincesName").setText(order.RecipientProvincesName));
		ExOrder.addContent(new Element("RecipientCityName").setText(order.RecipientCityName));
		ExOrder.addContent(new Element("CustomAgentCode").setText(order.CustomAgentCode));
		ExOrder.addContent(new Element("CustomAgentName").setText(order.CustomAgentName));
		ExOrder.addContent(new Element("CustomTradeCountry").setText(order.CustomTradeCountry));
		ExOrder.addContent(new Element("CustomConsigneeCountryCode").setText(order.CustomConsigneeCountryCode));
		ExOrder.addContent(new Element("CustomConsigneePhoneNumber").setText(order.CustomConsigneePhoneNumber));
		ExOrder.addContent(new Element("CustomTransportTypeCode").setText(order.CustomTransportTypeCode));
		ExOrder.addContent(new Element("TransportName").setText(order.TransportName));
		ExOrder.addContent(new Element("CustomPackagingTypeCode").setText(order.CustomPackagingTypeCode));

		Declaration.addContent(ExOrder);
		root.addContent(Declaration);

		Element GoodsLists = new Element("GoodsLists");
		for (int i = 0; i < goods.size(); i++) {
			Element Goods = new Element("Goods");
			Goods.addContent(new Element("GoodsNo").setText(goods.get(i).GoodsNo));
			Goods.addContent(new Element("Qty").setText(goods.get(i).Qty));
			Goods.addContent(new Element("DecPrice").setText(goods.get(i).DecPrice));
			Goods.addContent(new Element("DecTotal").setText(goods.get(i).DecTotal));
			Goods.addContent(new Element("GrossWt").setText(goods.get(i).GrossWt));
			Goods.addContent(new Element("NetWt").setText(goods.get(i).NetWt));
			Goods.addContent(new Element("Nots").setText(goods.get(i).Nots));
			Goods.addContent(new Element("GoodsBatchNo").setText(goods.get(i).GoodsBatchNo));
			Goods.addContent(new Element("CustomConversionFactor").setText(goods.get(i).CustomConversionFactor));
			Goods.addContent(new Element("CustomOriginCountryCode").setText(goods.get(i).CustomOriginCountryCode));
			GoodsLists.addContent(Goods);
		}
		Declaration.addContent(GoodsLists);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);
		String filepath = propertyUtil.getCk_file_path();
		String filename = "003_" + TimeUtil.getTimeString2() + "_" + FileUtil.get4RandomString() + ".xml";
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + File.separator + filename));

		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			fm = null;
			xmlOutputter = null;
		}

		isSuccess = FTPClientUtil.transferFile(Config.STOCKOUT_IP, Config.STOCKOUT_PORT, Config.STOCKOUT_USERNAME,
				Config.STOCKOUT_PASSWORD, Config.STOCKOUT_UPLOAD_FILEPATH, true, filepath + File.separator + filename,
				"", "");

		return isSuccess;

	}

	/**
	 * 物流 入库
	 * 
	 * @param order
	 * @param list
	 * @throws Exception
	 */

	public boolean createImmigrationXml(Order2Immigration order, List<OrderGood2Immigration> list) throws Exception {
		boolean isSuccess = false;
		if (list == null || list.isEmpty()) {
			logger.info("订单中没有商品信息");

		}
		Element root = new Element("Manifest");
		Document document = new Document(root);
		Element head = new Element("Head");
		head.addContent(new Element("MessageID").setText(order.MessageID));
		head.addContent(new Element("FunctionCode").setText(order.FunctionCode));
		head.addContent(new Element("MessageType").setText(order.MessageType));
		head.addContent(new Element("SenderID").setText(order.SenderID));
		head.addContent(new Element("SendTime").setText(order.SendTime));
		root.addContent(head);
		Element Declaration = new Element("Declaration");
		Element InOrder = new Element("InOrder");
		InOrder.addContent(new Element("EntInsideNo").setText(order.EntInsideNo));
		InOrder.addContent(new Element("InputDate").setText(order.InputDate));
		InOrder.addContent(new Element("DrDate").setText(order.DrDate));
		InOrder.addContent(new Element("Nots").setText(order.Nots));
		InOrder.addContent(new Element("CountryCode").setText(order.CountryCode));
		InOrder.addContent(new Element("Ciqbcode").setText(order.Ciqbcode));
		InOrder.addContent(new Element("CiqBargainnoo").setText(order.CiqBargainnoo));
		InOrder.addContent(new Element("CiqShippername").setText(order.CiqShippername));
		InOrder.addContent(new Element("CiqConsigneename").setText(order.CiqConsigneename));
		InOrder.addContent(new Element("CiqPortload").setText(order.CiqPortload));
		InOrder.addContent(new Element("CiqPortdis").setText(order.CiqPortdis));
		InOrder.addContent(new Element("CiqTradecode").setText(order.CiqTradecode));
		InOrder.addContent(new Element("CiqCountryload").setText(order.CiqCountryload));
		InOrder.addContent(new Element("CiqCbeComcode").setText(order.CiqCbeComcode));
		InOrder.addContent(new Element("BillNo").setText(order.BillNo));
		InOrder.addContent(new Element("Tool").setText(order.Tool));
		InOrder.addContent(new Element("LogisticsProviders").setText(order.LogisticsProviders));
		InOrder.addContent(new Element("CustomerCode").setText(order.CustomerCode));
		InOrder.addContent(new Element("CiqCtType").setText(order.CiqCtType));
		InOrder.addContent(new Element("CtNumber").setText(order.CtNumber));
		InOrder.addContent(new Element("CarNo").setText(order.CarNo));
		InOrder.addContent(new Element("TransportMode").setText(order.TransportMode));
		Declaration.addContent(InOrder);
		root.addContent(Declaration);

		Element GoodsLists = new Element("GoodsLists");

		for (int i = 0; i < list.size(); i++) {
			Element Goods = new Element("Goods");
			Goods.addContent(new Element("GoodsNo").setText(list.get(i).GoodsNo));
			Goods.addContent(new Element("Qty").setText(list.get(i).Qty));
			Goods.addContent(new Element("DecPrice").setText(list.get(i).DecPrice));
			Goods.addContent(new Element("DecTotal").setText(list.get(i).DecTotal));
			Goods.addContent(new Element("GrossWt").setText(list.get(i).GrossWt));
			Goods.addContent(new Element("NetWt").setText(list.get(i).NetWt));
			Goods.addContent(new Element("Nots").setText(list.get(i).Nots));
			Goods.addContent(new Element("CiqPacktype").setText(list.get(i).CiqPacktype));
			Goods.addContent(new Element("CiqBuyfromcity").setText(list.get(i).CiqBuyfromcity));
			Goods.addContent(new Element("CiqGoodsbatchno").setText(list.get(i).CiqGoodsbatchno));
			Goods.addContent(new Element("CiqCtSize").setText(list.get(i).CiqCtSize));
			Goods.addContent(new Element("CiqCtType").setText(list.get(i).CiqCtType));
			Goods.addContent(new Element("CtNumber").setText(list.get(i).CtNumber));
			Goods.addContent(new Element("BarCode").setText(list.get(i).BarCode));
			Goods.addContent(new Element("FirstStatutoryUnitCode").setText(list.get(i).FirstStatutoryUnitCode));
			Goods.addContent(new Element("FirstStatutoryQuantity").setText(list.get(i).FirstStatutoryQuantity));
			GoodsLists.addContent(Goods);
		}
		Declaration.addContent(GoodsLists);

		Format fm = Format.getPrettyFormat();
		fm.setEncoding("utf-8");
		XMLOutputter xmlOutputter = new XMLOutputter(fm);

		String filepath = propertyUtil.getRk_file_path();
		logger.info(filepath);
		String filename = "002_" + TimeUtil.getTimeString2() + "_" + FileUtil.get4RandomString() + ".xml";
		logger.info(filename);
		try {
			xmlOutputter.output(document, new FileOutputStream(filepath + "/" + filename));
			logger.info("报文创建完成");
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {

			xmlOutputter = null;
		}
		isSuccess = FTPClientUtil.transferFile(Config.STOCKOUT_IP, Config.STOCKOUT_PORT, Config.STOCKOUT_USERNAME,
				Config.STOCKOUT_PASSWORD, Config.STOCKOUT_UPLOAD_FILEPATH, true, filepath + File.separator + filename,
				"", "");
		if (isSuccess) {
			logger.info("订单号为：" + order.getEntInsideNo() + "的订单南沙国际物流入库报文上传成功!!!");
		} else {
			logger.info("订单号为：" + order.getEntInsideNo() + "的订单南沙国际物流入库报文上传失败!!!");
		}
		return isSuccess;

	}

	/**
	 * 启邦物流
	 * 
	 * @param order
	 * @param goods
	 * @throws Exception
	 */

	public Receiver createQiBangXml(Order2QiBang order, List<OrderGood2QiBang> goods) throws Exception {
		if (goods == null || goods.isEmpty()) {
			logger.info("订单中没有商品信息");
		}

		Element root = new Element("request");
		Document document = new Document(root);
		root.addContent(new Element("store_code").setText(order.getStore_code()));
		root.addContent(new Element("order_code").setText(order.getOrder_code()));
		root.addContent(new Element("order_type").setText(order.getOrder_type()));
		root.addContent(new Element("order_source").setText(order.getOrder_source()));
		root.addContent(new Element("order_create_time").setText(order.getOrder_create_time()));
		root.addContent(new Element("v_ieflag").setText(order.getV_ieflag()));
		root.addContent(new Element("v_consignor_code").setText(order.getV_consignor_code()));
		root.addContent(new Element("v_card_type").setText(order.getV_card_type()));
		root.addContent(new Element("v_transport_code").setText(order.getV_transport_code()));
		root.addContent(new Element("v_package_typecode").setText(order.getV_package_typecode()));
		root.addContent(new Element("v_qy_state").setText(order.getV_qy_state()));
		root.addContent(new Element("v_master_good_name").setText(order.getV_master_good_name()));
		root.addContent(new Element("n_kos").setText(order.getN_kos()));
		root.addContent(new Element("v_traf_name").setText(order.getV_traf_name()));
		root.addContent(new Element("tms_service_code").setText(order.getTms_service_code()));
		root.addContent(new Element("tms_order_code").setText(order.getTms_order_code()));
		root.addContent(new Element("prev_order_code").setText(order.getPrev_order_code()));
		root.addContent(new Element("totalmailno").setText(order.getTotalmailno()));
		root.addContent(new Element("receiver_info").setText(order.getReceiver_info()));
		root.addContent(new Element("sender_info").setText(order.getSender_info()));
		Element order_item_list = new Element("order_item_list");
		for (int i = 0; i < goods.size(); i++) {
			Element order_item = new Element("order_item");
			order_item.addContent(new Element("v_goods_regist_no").setText(goods.get(i).getV_goods_regist_no()));
			order_item.addContent(new Element("order_item_id").setText(goods.get(i).getOrder_item_id()));
			order_item.addContent(new Element("item_id").setText(goods.get(i).getItem_id()));
			order_item.addContent(new Element("item_name").setText(goods.get(i).getItem_name()));
			order_item.addContent(new Element("item_code").setText(goods.get(i).getItem_code()));
			order_item.addContent(
					new Element("inventory_type").setText(String.valueOf(goods.get(i).getInventory_type())));
			order_item.addContent(new Element("item_quantity").setText(goods.get(i).getItem_quantity()));
			order_item.addContent(new Element("item_price").setText(goods.get(i).getItem_price()));
			order_item.addContent(new Element("item_version").setText(goods.get(i).getItem_version()));
			order_item.addContent(new Element("attributes").setText(goods.get(i).getAttributes()));
			order_item.addContent(new Element("cus_code").setText(goods.get(i).getCus_code()));
			order_item.addContent(new Element("sku_code").setText(goods.get(i).getSku_code()));
			order_item.addContent(new Element("item_spec").setText(goods.get(i).getItem_spec()));

			order_item_list.addContent(order_item);
		}
		root.addContent(order_item_list);
		root.addContent(new Element("package_count").setText(String.valueOf(order.getPackage_count())));
		root.addContent(new Element("delivery_method").setText(order.getDelivery_method()));
		root.addContent(new Element("remark").setText(order.getRemark()));
		root.addContent(new Element("order_ename").setText(order.getOrder_ename()));
		root.addContent(new Element("order_phone").setText(order.getOrder_phone()));
		root.addContent(new Element("order_cardno").setText(order.getOrder_cardno()));
		root.addContent(new Element("freight").setText(order.getFreight()));
		root.addContent(new Element("tax").setText(order.getTax()));
		root.addContent(new Element("Insurance_fee").setText(order.getInsurance_fee()));
		/**
		 * 以下注释代码为生成XML文件并保存到指定目录中
		 */

		ByteArrayOutputStream byteRsp = new ByteArrayOutputStream();
		XMLOutputter xmlOut = new XMLOutputter();
		try {
			xmlOut.output(document, byteRsp);
		} catch (Exception e) {
			e.printStackTrace();
		}
		// String packetXmlString = FileUtil.readFile(filepath + "/" +
		// filename);
		String packetXmlString = byteRsp.toString();
		System.out.println(packetXmlString);
		int begin_index = packetXmlString.indexOf("<?");
		int end_index = packetXmlString.indexOf(">");
		String head = packetXmlString.substring(begin_index, end_index + 1);
		String content = packetXmlString.replace(head, "");// 去掉XML头申明
		String data_digest = new String(
				Base64.encodeBase64((Base64_MD5Util.md5(content + Config.QB_KEY, "UTF-8")).getBytes()), "UTF-8");
		String xml = HttpRequestUtils.postMethod(Config.QB_URL, content, data_digest);
		SAXBuilder builder = new SAXBuilder(false);
		Document doc = builder.build(new InputSource(new StringReader(xml)));
		Element roots = doc.getRootElement(); // 得到根元素
		Receiver receiver = new Receiver();
		Element success = roots.getChild("success");
		if (success.getValue().equals("true")) {
			receiver.setStatus("1");
			receiver.setCode("");
			receiver.setInfo("成功");
		} else {
			receiver.setStatus("0");
			receiver.setCode(roots.getChild("errorCode").getValue());
			receiver.setInfo(roots.getChild("errorMsg").getValue());
		}
		receiver.setName("启邦物流");
		receiver.setDate(new Date());
		receiver.setOrder_id(order.getOrder_code());
		return receiver;

	}

	/**
	 * 获取远程FTP目录下的文件
	 * 
	 * @param ip
	 * @param port
	 * @param username
	 * @param password
	 * @param localFilePath
	 * @param remoteFilePath
	 * @throws Exception
	 */

	public List<String> downloadXml(String ip, String port, String username, String password, String localFilePath,
			String remoteFilePath, int type) throws Exception {
		List<String> xmList = FTPClientUtil.ftpDownFiles(ip, port, username, password, remoteFilePath, localFilePath,
				type);
		return xmList;
	}

	/**
	 * 批量删除远程目录下的文件
	 * 
	 * @param ip
	 * @param port
	 * @param userName
	 * @param userPassword
	 * @param remoteFile
	 * @throws Exception
	 */
	public void deleteXmlFile(String ip, String port, String userName, String userPassword, String remoteFile)
			throws Exception {
		FTPClientUtil.deleteFiles(ip, Integer.valueOf(port), userName, userPassword, remoteFile);
	}

	/**
	 * 解析回执报文
	 * 
	 * @param localPath
	 * @param element
	 */
	public void parserCustomXml(String localPath) throws Exception {
		File file = new File(localPath);
		File[] files = file.listFiles();
		if (files != null && files.length > 0) {
			int len = files.length;
			for (int i = 0; i < len; i++) {
				File file_ = new File(localPath + File.separator + files[i].getName());
				if (file_.getName().endsWith(".txt") || file_.getName().endsWith(".xml")) {
					String fileName = file_.getName();
					fileName = fileName.replace(".txt", ".xml");
					file_.renameTo(new File(localPath + File.separator + fileName));
					String receiverXMl = null;
					receiverXMl = FileUtil.readFile(localPath + File.separator + fileName);

					receiverXMl = AESMessageSigner.decrypt(receiverXMl);
					// 将原来的 XML文件内容清空

					File file1 = new File(localPath + "/" + fileName);
					FileWriter writer = new FileWriter(file1);
					writer.write("");
					writer.close();
					file = null;
					FileUtil.saveFile(localPath + "/" + fileName, receiverXMl);

				}
			}

		}

	}

	/**
	 * 解析XML文件
	 * 
	 * @param localPath
	 * @param element
	 * @throws JDOMException
	 * @throws IOException
	 */

	public void parserXml(String localPath, String element_1) throws JDOMException, IOException {
		File file = new File(localPath);
		File[] files = file.listFiles();
		if (files.length > 0) {
			for (int i = 0; i < files.length; i++) {
				File f = files[i];
				SAXBuilder builder = new SAXBuilder();
				Document document = builder.build(localPath + "/" + f.getName());
				Element root = document.getRootElement();
				List persons = root.getChildren(element_1);
				if (!persons.isEmpty()) {
					for (int j = 0; j < persons.size(); j++) {
						Element person = (Element) persons.get(j);
						System.out.println(person.getName());
						List pros = person.getChildren();
						if (!pros.isEmpty()) {
							for (int m = 0; m < pros.size(); m++) {
								Element element_ = (Element) pros.get(m);
								System.out.println(element_.getName() + "->>>" + element_.getValue());
							}
						} else {
							System.out.println(person.getName() + "--" + person.getValue());
						}

					}
				}

			}

		}

	}

	public void analysisPaymentXml(String filePath, String... strings) throws Exception {
		File file = new File(filePath);
		if (!file.exists()) {
			logger.info("目录不存在");
			return;
		}
		File[] files = file.listFiles();
		if (files.length == 0) {
			logger.info("目录中没有文件");
			return;
		}
		SAXBuilder builder = new SAXBuilder();
		for (int i = 0; i < files.length; i++) {
			Document document = builder.build(new File(filePath + "/" + files[i].getName()));
			Element root = document.getRootElement();
			List<Element> elements = root.getChildren(strings[0]);
			for (Element element : elements) {
				System.out.println(element.getName());
				if (!element.isRootElement()) {
					System.out.println(element.getChild(strings[1]).getName());

				}

			}
			List<Element> elements2 = root.getChildren(strings[2]);
			for (Element element : elements2) {
				if (!element.isRootElement()) {
					List<Element> elements3 = element.getChildren();
					for (Element element2 : elements3) {
						System.out.println(element2.getChild(strings[3]).getName());

					}

				}

			}

		}

	}

	/**
	 * 移除指定路径下所有文件
	 * 
	 * @param strPath
	 */
	public void removeAllFile(String strPath) {

		File file = new File(strPath);
		if (!file.exists()) {

			return;
		}
		if (!file.isDirectory()) {

			return;
		}
		String[] fileList = file.list();
		File tempFile = null;
		for (int i = 0; i < fileList.length; i++) {
			if (strPath.endsWith(File.separator)) {
				tempFile = new File(strPath + fileList[i]);
			} else {
				tempFile = new File(strPath + File.separator + fileList[i]);
			}
			if (tempFile.isFile()) {
				if (tempFile.canExecute())
					tempFile.delete();
			}
			if (tempFile.isDirectory()) {
				removeAllFile(strPath + "/" + fileList[i]);// 删除文件夹里面的文件
				// removeFolder(strPath + "/" + fileList[i]);// 删除文件夹
			}
		}
	}

	/**
	 * 将生成的XML文件保存到指定目录
	 * 
	 * @param doc
	 */
	public static void saveXML(Document doc, String filePath) {
		// 将doc对象输出到文件
		try {
			// 创建xml文件输出流
			XMLOutputter xmlopt = new XMLOutputter();
			// 创建文件输出流
			FileWriter writer = new FileWriter(filePath);
			// 指定文档格式
			Format fm = Format.getPrettyFormat();
			// fm.setEncoding("GB2312");
			xmlopt.setFormat(fm);
			// 将doc写入到指定的文件中
			xmlopt.output(doc, writer);
			writer.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
